import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    ListView,
    ScrollView,
    Text,
    TouchableOpacity,
    Dimensions,
    Slider,
    Image,
} from 'react-native'
import values from 'lodash/values';
import keys from 'lodash/keys';
import assign from 'lodash/assign';
import {  MtLoadingModal, MtLabelBar } from 'martian-ui';
import NavigationBar from '../../components/common/NavigationBar'
import { BoxShadow } from 'react-native-shadow'
import { Switch } from 'react-native-switch';
import ChooseItems from '../../components/styleCompoent/ChooseItems';
import LabelBarWithSwitch from '../../components/styleCompoent/LabelBarWithSwitch';
import TwoLabelBarAndSlider from '../../components/styleCompoent/TwoLabelBarAndSlider';
import LabelBarWithShadow from '../../components/styleCompoent/LabelBarWithShadow';
import { fetchDeviceDetailById, controlDevice } from '../../action/girlAction';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux';
const EntityLabels = require('../../constants/entities');
// 取得屏幕的宽高Dimensions
const { width, height } = Dimensions.get('window');

class AirConditioning extends Component {
  constructor(props) {
    super(props)
    this.state = {
      modelList: [{
        id: 1,
        name: '制冷',
        icon: 'refrigeration'
      }, {
        id: 2,
        name: '制热',
        icon: 'heating'
      }, {
        id: 3,
        name: '送风',
        icon: 'ventilation'
      }, {
        id: 4,
        name: '除湿',
        icon: 'dehumidification'
      }],
      currentModel: 0,

      switchValue: 0,
      WorkMode: 2,
      WindSpeed:2,
      TargetTemperature: 16,
      roomTemperature: 0,
      temperature: 0,
      windSpeedModelList: [{
        id: 1,
        name: '自动',
      },{
        id: 2,
        name: '低速',
      },{
        id: 3,
        name: '中速',
      },{
        id: 4,
        name: '高速',
      }],
      currentWindSpeedModel: 0,
    }
    this.dataSource = new ListView.DataSource({
      rowHasChanged: ((row1, row2) => row1 !== row2)
    })
  }

  controlAir(params){
    const {controlDevice, deviceId} = this.props;
    controlDevice(params, deviceId);
  }
  componentDidMount() {

  }
  componentWillMount() {
    const { fetchDeviceDetailById,  deviceId} = this.props;
    fetchDeviceDetailById(deviceId);
    this.convertPropsToStates(this.props);

  }
  convertPropsToStates(props) {
    const {devicesEntities, deviceId,  actions, update } = props;
    const device = devicesEntities[deviceId];

    let data;
    if(update === 'update'){
      actions && actions.forEach(ele => {
        if (ele.switch === '1' || ele.switch === 'true'){
          this.setState({
            value: true,
          })
        }

        if (ele.targetTemperature){
          this.setState({
            TargetTemperature: ele.targetTemperature,
          })
        }

        if (ele.windSpeed){
          this.setState({
            WindSpeed: ele.windSpeed,
          })
        }
        if (ele.workMode){
          this.setState({
            WorkMode: ele.workMode,
          })
        }

      })

    }else {
      if (device && device.status){
        if (device.status.switch === 'true' || device.status.switch === '1'){
          this.setState({
            value: true,
          })
        }
        else {
          this.setState({
            value: false,
          })
        }
        if (device.status.targetTemperature){
          this.setState({
            TargetTemperature: device.status.targetTemperature,
          })
        }

        if (device.status.windSpeed){
          this.setState({
            WindSpeed: device.status.windSpeed,
          })
        }
        if (device.status.workMode){
          this.setState({
            WorkMode: device.status.workMode,
          })
        }
      }
    }

    const newState = assign({
      device
    });

    if (newState) {
      this.setState(newState);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.convertPropsToStates((nextProps));
  }



  render() {
    const {switchValue, WindSpeed, WorkMode, windSpeedModelList, TargetTemperature, device} = this.state;
    const { devicesIsFetching} = this.props;
    const status = device && device.status;


    const airParams= {
      CurrentTemperature: 20,//22-55
      WindSpeed: WindSpeed,//2,3,4枚举值：2（低档） 3（中档） 4（高档
      Switch: switchValue,//0,1
      WorkMode:WorkMode,//枚举值：1（制冷） 2（制热） 3（送风） 4（除湿）
      TargetTemperature: TargetTemperature,//取值范围：16-32，间距：1, 单位：℃
    }
    const rightElement = <Text style={styles.rightText} onPress={this._rightIconEvent}>保存</Text>
    const { update} = this.props;
    return (

        <View style={styles.container}>
          <MtLoadingModal
            visible={devicesIsFetching}
            tip="加载设备"
          />
          <NavigationBar
            title={'空调'}
            statusBar={{backgroundColor: '#F4F4F4', barStyle: 'dark-content'}}
            navigator={this.props.navigator}
            style={{backgroundColor: '#F4F4F4'}}
            rightButton={ update === 'update' ? rightElement : null}
          />
          <ScrollView showsVerticalScrollIndicator={false} style={{paddingTop: 7}}>
            <LabelBarWithSwitch
                barWidth={width-30}
                barHeight={68}
                title="电源"
                changeValue={(value)=>{
                  this.setState({value: value},()=>{
                    const newAirParams = {'Switch': value ? "1" : '0'}
                    update !== 'update' && this.controlAir(newAirParams);
                  })
                }}
                value={this.state.value}
            />
            <TwoLabelBarAndSlider
                barWidth={width-30}
                barHeight={194}
                containerStyle={{marginTop: 15}}
                firstLineTitle={'室内温度'}
                secondLineTitle={'温度设置'}
                maximumValue={33}
                minimumValue={16}
                firstLineValue={  '16'}
                value={this.state.TargetTemperature}
                chooseValue={(TargetTemperature)=>{
                  this.setState({TargetTemperature},()=>{
                    const newAirParams = {'TargetTemperature': TargetTemperature}
                    update !== 'update' && this.controlAir(newAirParams);
                  })
                }}

            />

            <View style={styles.modelView}>
              <Text style={styles.modelTitle}>工作模式</Text>
              <ListView style = {styles.modelList}
                        dataSource = {this.dataSource.cloneWithRows(this.state.modelList)}
                        renderRow = {this._renderRow.bind(this)}
                        horizontal = {true}
                        showsHorizontalScrollIndicator = {false}
              />
            </View>
            <ChooseItems
                barWidth={width-30}
                barHeight={154}
                containerStyle={{margin: 15}}
                title="风速选择"
                data={windSpeedModelList}
                chooseItem={ this.state.WindSpeed || '1'}
                chooseMode={(WindSpeed)=>{
                  this.setState({WindSpeed},()=>{
                    const newAirParams = {'WindSpeed': WindSpeed}
                    update !== 'update' && this.controlAir(newAirParams);
                  })
                }}
            />

            <LabelBarWithShadow
                barWidth={width-30}
                barHeight={68}
                containerStyle={{marginTop: 15}}
                title={'预约'}
                rightValue={'未设置'}
            />
          </ScrollView>
        </View>

    )
  }
  _getShadowOpt(data) {
    return {
      width: data.width,
      height: data.height,
      color: "#999999",
      border: 3,
      radius: 6,
      opacity: 0.1,
      x: 0,
      y: 3,
      style: data.style
    }
  }
  _onModelPressButton(rowData) {
    const {switchValue, WindSpeed, WorkMode, TargetTemperature} = this.state;
    const { update} = this.props;
    this.setState({WorkMode: rowData.id},()=>{
      const newAirParams = {'WorkMode': rowData.id};
      update !== 'update' && this.controlAir(newAirParams);
    })

  }
  // 返回一个Item
  _renderRow(rowData) {
    return (
        <TouchableOpacity onPress = {this._onModelPressButton.bind(this, rowData)}>
            <BoxShadow setting={this._getShadowOpt({
              width: 76,
              height: 76,
              style: {marginTop: 10, marginRight: 13, marginBottom: 10}
            })}>
              <View style = {styles.modelItem}>
                <Image source={require('../../img/dehumidification.png')}></Image>
                <Text style = {styles.modelText}>{rowData.name}</Text>
              </View>
            </BoxShadow>
        </TouchableOpacity>
    )
  }
  _rightIconEvent() {
    const {  value, WindSpeed, TargetTemperature, WorkMode  } =this.state;
    const {  setParams, isUpdate} =this.props;

    isUpdate(true);
    const params = {'workMode': WorkMode,'targetTemperature': TargetTemperature,'windSpeed': WindSpeed, 'value': value ? '1': '0' }
    setParams(params);

  }

}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F4F4F4',
    flex: 1,
  },
  flex: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 20,
    paddingRight: 20,
  },
  power: {
    height: 68,
    width: width - 30,
    backgroundColor: '#fff',
    borderRadius: 6,
  },
  powerText: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333333',
  },
  powerSwitch: {
  },
  temperature: {
    marginTop: 20,
  },
  temperatureTitle: {
    color: '#333333',
    fontSize: 13
  },
  temperatureText: {
    color: '#444444',
    fontSize: 24
  },
  sliderView: {
    marginTop: 25,
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 20,
    paddingRight: 20,
  },
  slider: {
    flex: 1,
  },
  settings: {
    height: 194,
    width: width - 30,
    borderRadius: 6,
    backgroundColor: '#fff',
  },
  modelView: {
    marginTop: 30,
    width: width - 30,
    marginLeft: 15
  },
  modelTitle: {
    textAlign: 'left',
    color: '#333333',
    fontWeight: 'bold',
  },
  modelList: {
    paddingBottom: 10
  },
  modelItem: {
    width: 76,
    height: 76,
    backgroundColor: '#fff',
    borderRadius: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modelText: {
    color: '#333333',
    fontSize: 11,
    marginTop: 5,
  },
  windSpeedView: {
    height: 154,
    width: width - 30,
    borderRadius: 6,
    backgroundColor: '#fff',
  },
  windSpeedTitle: {
    marginTop: 24,
    marginLeft: 20,
  },
  windSpeedContent: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingLeft: 22,
    paddingRight: 22,
    marginTop: 32,
    position: 'relative',
  },
  windSpeedItem: {
    width: 24,
  },
  weedItem: {
    alignItems: 'center',
    zIndex: 10,
  },
  round: {
    width: 14,
    height: 14,
    backgroundColor: '#EAEAEA',
    borderRadius: 7,
    marginTop: 10,
  },
  lineView: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    left: 0,
  },
  line: {
    width: width - 98,
    height: 4,
    backgroundColor: '#EAEAEA',
    position: 'absolute',
    left: 34,
    top: 109,
  },
  reservationView: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  reservationText: {
    color: '#777777',
    fontSize: 12,
    marginRight: 16,
  },
  transform: {
    transform: [{rotate: '180deg'}]
  }
})

function mapDispatchToProps(dispatch) {
  const actions = {
    fetchDeviceDetailById,
    controlDevice
  };
  return bindActionCreators(actions, dispatch);
}

function mappingStateToProps(state, ownProps) {
  const entities= state['entities'];
  const isFetching= state['isFetching'];
  const devicesIsFetching = isFetching['fetchDeviceDetailById'];
  const devicesEntities = entities[EntityLabels.devices];




  return {
    devicesEntities,
    devicesIsFetching,
  }
}

module.exports = connect(mappingStateToProps, mapDispatchToProps)(AirConditioning);
